import { cloneElement, isValidElement, useState } from "react";
import { Arrow } from "../svg/svg";
import classNames from "classnames";
import "./select.scss";
interface SelectProps {
  // children
  children: React.ReactElement<ItemProps>[];
  // 可控类名
  className?: string;
  // 默认选中 该数据必须存在children中
  defaultValue?: any | React.ReactElement;
  // 宽度
  width?: string;
}

interface ItemProps {
  children: any;
  className?: string;
  // 每个子组件携带的数据
  value: string | number;
  // 更改是否显示的状态并且修改默认选中数据 调用子组件时请勿使用
  onSetIsOpen?: (e: any) => void;
  // 点击子组件时触发的函数 无返回值 用来更改外部状态
  onChange?: (e: any) => void;
  // 控制子组件的active类 调用子组件时请勿使用
  active?: string;
}

export const Select = ({
  children,
  className,
  defaultValue,
  width,
  ...rest
}: SelectProps) => {
  const selectClassName = (): string => {
    return classNames("dashboard_select", className);
  };

  const [selectedValue, setSelectedValue] = useState(defaultValue);

  const childrenClick = (value) => {
    setIsOpen(false);
    setSelectedValue(value);
  };

  const [isOpen, setIsOpen] = useState(false);
  const childrenWithProps = children?.map((child, index) => {
    if (isValidElement(child) && typeof child.props === "object") {
      return cloneElement(child, {
        ...child.props,
        key: index,
        onSetIsOpen: (e) => childrenClick(e),
        active: selectedValue,
      });
    }
    return child;
  });

  return (
    <>
      <div className="dashboard_select_box" style={{ width: width }}>
        <div
          className={selectClassName()}
          {...rest}
          data-value={selectedValue}
          onClick={() => setIsOpen(!isOpen)}
        >
          <span className="selected_defaultvalue">{selectedValue}</span>
          <div className="select_arrow_box">
            <Arrow color="#c127b9" className="select_arrow" />
          </div>
        </div>
        {isOpen && (
          <div className="select_item_box">
            <ul className="select_item_list">{childrenWithProps}</ul>
          </div>
        )}
      </div>
    </>
  );
};
const Item = ({
  children,
  value,
  className,
  onSetIsOpen,
  onChange,
  active,
  ...rest
}: ItemProps): React.ReactElement => {
  const handleChange = (e: React.MouseEvent<HTMLLIElement>) => {
    let target = e.currentTarget;
    if (target instanceof HTMLLIElement) {
      let value = target.getAttribute("data-value");
      onChange?.(value);
      onSetIsOpen?.(children);
    }
  };

  return (
    <>
      <li
        className={classNames(
          "dashboard_select_item",
          className,
          children == active ? "active" : ""
        )}
        data-value={value}
        {...rest}
        onClick={(e) => handleChange(e)}
      >
        {children}
      </li>
    </>
  );
};

Select.Item = Item;
